package csv;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class CSVParser
{
  private final BufferedReader reader;
  private File location;
  private int cursorPosition;
  private String nextLine;
  private String[] columnNames;

  public CSVParser(String location)
    throws IOException
  {
    this.location = new File(location);
    this.reader = new BufferedReader(new FileReader(new File(location)));
    initColumnNames();
    this.cursorPosition = 0;
  }

  public CSVParser(File inputFile) throws IOException {
    this.location = inputFile;
    this.reader = new BufferedReader(new FileReader(inputFile));
    initColumnNames();
    this.cursorPosition = 0;
  }

  private void initColumnNames() throws IOException {
    this.nextLine = this.reader.readLine();
    String[] names = getNext();
    if (names == null) {
      throw new IOException("Invalid File Format: File Was Empty");
    }
    setColumnNames(names);
  }

  public String[] getColumnNames() {
    return this.columnNames;
  }

  private void setColumnNames(String[] columnNames) {
    this.columnNames = columnNames;
  }

  public CSVFile getCSVFile() throws IOException {
    CSVFile result = new CSVFile(this.columnNames);
    while (hasNext()) {
      String[] test = getNext();
      if (test.length == this.columnNames.length)
        result.addRow(test);
    }
    return result;
  }

  public boolean hasNext() {
    return this.nextLine != null;
  }

  public String[] getNext() throws IOException {
    if (!hasNext()) {
      return null;
    }
    String[] values = this.nextLine.split(",");
    for (int i = 0; i < values.length; i++)
      values[i] = values[i].replace('"', ' ').trim();
    this.cursorPosition += 1;
    this.nextLine = this.reader.readLine();
    return values;
  }

  public String getElementByNumber(int columnNumber) {
    String[] values = this.nextLine.split(",");
    if (columnNumber >= values.length) {
      return "";
    }
    return values[columnNumber] = values[columnNumber].replace('"', ' ').trim();
  }

  public String getElementByName(String columnName) {
    for (int i = 0; i < this.columnNames.length; i++)
      if (this.columnNames[i] == columnName)
        return getElementByNumber(i);
    return "";
  }

  public int getCursorPosition() {
    return this.cursorPosition;
  }

  public File getLocation() {
    return this.location;
  }
}